package com.example.gobang.api;

import com.example.gobang.game.MatchRequest;
import com.example.gobang.game.MatchRequse;
import com.example.gobang.game.Matcher;
import com.example.gobang.game.onlineUserManager;
import com.example.gobang.model.User;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.juli.OneLineFormatter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
@Component
public class MatchApi extends TextWebSocketHandler {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Autowired
    public onlineUserManager onlineUserManager1;
    @Autowired
    private Matcher matcher;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        try {
            User user = (User) session.getAttributes().get("user");
            if (onlineUserManager1.getFromGameHall(user.getUserId()) != null||onlineUserManager1.getFromGameRoom(user.getUserId())!=null) {

                MatchRequse response = new MatchRequse();

                response.setOk(true);

                response.setReason("当前禁止多开!");

                response.setMessage("repeatConnection");

                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                return;

            }
            onlineUserManager1.enterGameHall(user.getUserId(), session);
        }
            catch (NullPointerException e) {
                System.out.println("[MatchAPI.afterConnectionEstablished] 当前用户未登录!");
                MatchRequse response = new  MatchRequse();
                response.setOk(false);
                response.setReason("您尚未登录! 不能进行后续匹配功能!");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
            }

    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {

        User user = (User) session.getAttributes().get("user");


        String payload = message.getPayload();
        // 当前这个数据载荷是一个 JSON 格式的字符串, 就需要把它转成 Java 对象. MatchRequest

        MatchRequest request = objectMapper.readValue(payload, MatchRequest.class);
        MatchRequse response = new MatchRequse();
        if (request.getMessage().equals("startMatch")) {
            // 进入匹配队列

            matcher.add(user);
            // 把玩家信息放入匹配队列之后

            response.setOk(true);
            response.setMessage("startMatch");
        } else if (request.getMessage().equals("stopMatch")) {
            // 退出匹配队列

            matcher.remove(user);


            response.setOk(true);
            response.setMessage("stopMatch");
        } else {
            response.setOk(false);
            response.setReason("非法的匹配请求");
        }
        String jsonString = objectMapper.writeValueAsString(response);
        session.sendMessage(new TextMessage(jsonString));


    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {

        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession socketSession = onlineUserManager1.getFromGameHall(user.getUserId());
            if(socketSession==session){
                onlineUserManager1.exitGameHall(user.getUserId());
            }
            matcher.remove(user);
           // onlineUserManager1.exitGameHall(user.getUserId());
        }catch (NullPointerException e){
            e.printStackTrace();
//            MatchRequse matchRequse = new MatchRequse();
//            matchRequse.setOk(false);
//            matchRequse.setReason("尚未登录");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchRequse)));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession socketSession = onlineUserManager1.getFromGameHall(user.getUserId());
            if(socketSession==session){
                onlineUserManager1.exitGameHall(user.getUserId());
            }
            matcher.remove(user);
           // onlineUserManager1.exitGameHall(user.getUserId());
        }catch (NullPointerException e){
            e.printStackTrace();
//            MatchRequse matchRequse = new MatchRequse();
//            matchRequse.setOk(false);
//            matchRequse.setReason("尚未登录");
//            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(matchRequse)));
        }
    }
}
